package imgconvert

import (
	"os"

	"gopkg.in/gographics/imagick.v2/imagick"
)

// Squash 压缩
func Squash(src string, quality uint) (out string, err error) {
	imagick.Initialize()
	defer imagick.Terminate()
	mw := imagick.NewMagickWand()
	err = mw.ReadImage(src)
	if err != nil {
		return "", err
	}
	err = mw.SetImageCompressionQuality(quality)
	if err != nil {
		return "", err
	}

	err = mw.WriteImage(out)
	if err != nil {
		return "", err
	}
	return
}

// SquashFile 压缩
func SquashFile(file *os.File, quality uint) (out string, err error) {
	imagick.Initialize()
	defer imagick.Terminate()
	mw := imagick.NewMagickWand()
	err = mw.ReadImageFile(file)
	if err != nil {
		return "", err
	}
	err = mw.SetImageCompressionQuality(quality)
	if err != nil {
		return "", err
	}

	err = mw.WriteImage(out)
	if err != nil {
		return "", err
	}
	return
}

// SquashBlob 压缩
func SquashBlob(blob []byte, quality uint) (out string, err error) {
	imagick.Initialize()
	defer imagick.Terminate()
	mw := imagick.NewMagickWand()
	err = mw.ReadImageBlob(blob)
	if err != nil {
		return "", err
	}
	err = mw.SetImageCompressionQuality(quality)
	if err != nil {
		return "", err
	}

	err = mw.WriteImage(out)
	if err != nil {
		return "", err
	}
	return
}
